package com.kantboot.business.water.service.impl;

import com.kantboot.business.water.domain.dto.BusWaterGoodsDTOInClient;
import com.kantboot.business.water.domain.entity.BusWaterGoods;
import com.kantboot.business.water.repository.BusWaterGoodsRepository;
import com.kantboot.business.water.repository.BusWaterGoodsVOInClientRepository;
import com.kantboot.business.water.service.IBusWaterGoodsService;
import com.kantboot.util.core.param.PageParam;
import com.kantboot.util.core.result.PageResult;
import jakarta.annotation.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 提水点服务实现
 */
@Service
public class BusWaterGoodsServiceImpl
        implements IBusWaterGoodsService {

    @Resource
    private BusWaterGoodsRepository repository;

    @Resource
    private BusWaterGoodsVOInClientRepository clientRepository;


    @Override
    public PageResult getBodyData(PageParam<BusWaterGoods> param) {
        return PageResult.of(repository.getBodyData(param.getData(),param.getPageable()));
    }

    @Override
    public PageResult getBodyDataClient(PageParam<BusWaterGoodsDTOInClient> param) {
        String sortCode = param.getData().getSortCode();
        Sort sort = Sort.by(Sort.Order.desc("gmtModified"));
        if(BusWaterGoodsDTOInClient.SORT_CODE_SALE_PRICE_MIN.equals(sortCode)){
            // 按照销量排序
            sort = Sort.by(Sort.Order.asc("salePrice"));
        }else if(BusWaterGoodsDTOInClient.SORT_CODE_SALE_PRICE_MAX.equals(sortCode)){
            // 按照销量排序
            sort = Sort.by(Sort.Order.desc("salePrice"));
        }else if(BusWaterGoodsDTOInClient.SORT_CODE_SALE_VOLUME_MAX.equals(sortCode)){
            // 按照销量排序
            sort = Sort.by(Sort.Order.desc("saleVolume"));
        }
        Pageable pageable = PageRequest.of(param.getPageable().getPageNumber(), param.getPageable().getPageSize(), sort);
        return PageResult.of(clientRepository.getBodyDataClient(param.getData(),pageable));
    }

    @Override
    public BusWaterGoods getById(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public void removeBatch(List<BusWaterGoods> list) {
        for (BusWaterGoods busWaterGoods : list) {
            busWaterGoods.setIsDeleted(true);
            repository.save(busWaterGoods);
        }
    }

    @Override
    public void save(BusWaterGoods goods) {
        goods.setIsDeleted(false);
        goods.setSaleVolume(0L);
        repository.save(goods);
    }

    @Override
    public void addSalesVolume(Long id, Long salesVolume) {
        repository.addSalesVolume(id,salesVolume);
    }
}
